<?php
namespace app\resources\service;

use think\App;
use help\IpHelp;
use think\Event;
use think\Config;
use Swoole\Server;
use think\Request;
use think\facade\Cache;
use Swoole\Websocket\Frame;
use think\swoole\websocket\Room;
use app\resources\tasks\PushTask;

/**
 * 服务基类
 */
class WebSocketService
{

	protected $ws;
	protected $ip;
	protected $server;
    
    // 
    public function __construct(App $app, Server $server, Room $room, Event $event, Config $config)
    {
        $this->ws = app('\think\swoole\Websocket');
        $this->server = $server;
    }


	/**
     * "onOpen" listener.
     *
     * @param int $fd
     * @param Request $request
     */
    public function onOpen($fd, Request $request)
    {
        $this->ip = IpHelp::getOnlineIp();
        switch ($request->get('action')) {
            /**
             * 网页访问
             */
            case 'web':
              
                break;
            /**
             * 系统消息
             */
            case 'system':
                (new NodeService)->online($this->ip);
                break;
        }
        // 重补离线消息
        try {
            (new PushTask(['_action'=>'reset']))->reset($fd);
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    /**
     * "onMessage" listener.
     *
     * @param Frame $frame
     */
    public function onMessage(Frame $frame)
    {
        try {
            $message = json_decode($frame->data,true);
            if($message['type'] == 'cmd' || $message['type'] == 'cmd:host'){
                Cache::set(md5(json_encode($message['message'])),$message,3);
            }
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    /**
     * "onClose" listener.
     *
     * @param int $fd
     * @param int $reactorId
     */
    public function onClose($fd, $reactorId)
    {
        (new NodeService)->offline(IpHelp::getOnlineIp());
    }
    
	
}